import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import Cookie from 'vue-cookie'
import { Constant, Tools } from '@/utils'

const { TOKEN_KEY } = Constant
const { getMainRoute, joinView } = Tools

// 判断环境引入组件
// const theJoin = filePath => process.env.NODE_ENV === 'production' ? joinViewLazy(filePath) : joinView(filePath)

const globalRoutes = [
  {
    path: '/login',
    name: 'login',
    component: joinView('/Login')
  }
]

/*
  child: {
    path: /home/count,
    name: home_count,
    component: 页面,
    meta: {
      title: 名称
    }
  }
*/

export const router = createRouter({
  history: createWebHashHistory(),
  routes: [...globalRoutes]
})
// 是否为刷新进入页面
let registerRouteFresh = true

router.beforeEach(async (to, from, next) => {
  const globalPaths = globalRoutes.map(route => route.path)
  if (globalPaths.includes(to.path)) {
    next()
    return
  }

  const token = Cookie.get(TOKEN_KEY)
  if (!token) {
    next('/login')
    return
    // Cookie.set(TOKEN_KEY, '8c7582edbbab2715bfb6b9447181678b')
  }

  const projectId = localStorage.getItem('projectId') || ''
  const params = {}
  if (projectId) {
    params.projectId = projectId
  }
  if (registerRouteFresh) {
    console.log('first')
    const mainRoute = await getMainRoute(params)
    router.addRoute(mainRoute)
    router.addRoute({
      path: '/:pathMatch(.*)*',
      name: '404',
      component: joinView('/Error404')
    })
    next({ ...to, replace: true })
    registerRouteFresh = false
  } else {
    console.log('second')
    if (to.path === '/') {
      next({ path: to.matched[0].children[0].path, replace: true })
      return
    }
    const { path, meta } = to
    store.commit('Tabs/setMainPanes', { key: path, title: meta.title })
    next()
  }
})

export default function (app) {
  app.use(router)
}
